<template>
  <div class="index-container">
    <div class="main-header clearfix">
      <el-row>
       <el-col :xs="8" :sm="8" :md="8" :lg="8" :xl="8">
          <el-button type="primary"  icon="el-icon-plus" class="sureBtn"  size="medium"  @click="handleAdd" > 新 增 活 动</el-button>
        </el-col>
        <el-col :xs="16" :sm="16" :md="16" :lg="16" :xl="16">
          <div class="search fr">
            <div>
              <el-input  v-model="searchForm.title"   size="medium"  placeholder="活动名称"></el-input>
            </div>
            <div>
              <el-select v-model="searchForm.status" clearable @clear="clear" @change="clear" placeholder="请选择活动状态">
                <el-option label="未开始" value="1"></el-option>
                <el-option label="进行中" value="2"></el-option>
                <el-option label="已结束" value="3"></el-option>
              </el-select>
            </div>
            <div>
              <el-select v-model="searchForm.team_id" clearable @clear="clear" @change="clear" placeholder="负责站点">
                <el-option
                  v-for="item in teamList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </div>
            <el-button size="medium"   type="primary"   icon="el-icon-search"  class="fr"    @click="onSearch" > 搜索</el-button>
          </div>
        </el-col>
      </el-row>
    </div>
    <div class="main-content" style="height: calc(100vh - 250px);">
      <main-table
        :columns="tableColumns"
        :data="tableList"
        :loading="loading"
        :pagination="pagination"
         @getData="fetchTableList"
        wrapperHeight="calc(100% - 73px)" height="100%"
      >
      <el-table-column slot="status" label="状态" align="center">
        <template slot-scope="scope">
          <el-tag class="tag-cursor" v-if="scope.row.status == '0'" type="warning">申请中</el-tag>
          <el-tag class="tag-cursor" v-else-if="scope.row.status == '1'" type="success">未开始</el-tag>
          <el-tag class="tag-cursor" v-else-if="scope.row.status == '2'">进行中</el-tag>
          <el-tag class="tag-cursor" type="info" v-else>已结束</el-tag>
        </template>
      </el-table-column>
      <el-table-column slot="imgs" fixed="left" label="活动图片" width="150" align="center">
        <template slot-scope="scope">
          <img v-if="scope.row.img" class="contract-icon-img" :src="scope.row.img[0]" @click="handleBigImage(scope.row)" alt="">
          <span v-if="scope.row.status != '3'">活动结束后拍照</span>
          <el-button v-if="scope.row.status == '3'" type="primary" icon="el-icon-plus" @click="addImg(scope.row)">上传图片</el-button>
        </template>
      </el-table-column>

       <el-table-column slot="action" fixed="right" label="操作" width="300">
         <template slot-scope="scope">
           <el-button size="mini" type="primary" class="button-other-color" @click="startActivity(scope.row)">查看活动</el-button>
           <el-button size="mini" type="success" @click="edit(scope.row)">编辑</el-button>
           <el-button size="mini" type="success" :disabled="scope.row.status != '0'" @click="shenhe(scope.row)">审核</el-button>
           <el-button size="mini" type="danger" @click="cancelOrder(scope.row)">删除</el-button>
         </template>
       </el-table-column>

      </main-table>
    </div>

    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      width="1100px">
      <activity-add v-if="dialogVisible" @cancle="dialogVisible = false" :data="ruleForm" @load="load"></activity-add>
    </el-dialog>

   <!-- <el-dialog title="查看活动" v-if="dialogDetailsVisible" :close-on-click-modal="false" :visible.sync="dialogDetailsVisible" :append-to-body="true">
      <activity-details :data="ruleForm"></activity-details>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogDetailsVisible = false">关 闭</el-button>
      </span>
    </el-dialog> -->

    <el-dialog title="活动图片"  width="600px" :close-on-click-modal="false" :visible.sync="dialogImageVisible" :append-to-body="true">
      <img width="100%" :src="dialogImageUrl" alt="">
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="prev" :disabled="prevDisabled">{{ prevBtn }}</el-button>
        <el-button type="primary" @click="next" :disabled="nextDisabled">{{ nextBtn }}</el-button>
      </span>
    </el-dialog>

    <el-dialog
      title="添加活动图片"
      v-if="dialogImgVisible"
      :visible.sync="dialogImgVisible"
      @close="closeImgVisible"
      width="1100px"
      :close-on-click-modal="false">
        <el-form :model="imgForm" ref="imgForm">
          <el-form-item label="活动图片" prop="images">
            <el-upload
              action="#"
              class="manage-uploader"
              accept="image/*"
              list-type="picture-card"
              :limit="9"
              :file-list="fileList"
              :on-change="changePictureUploadAvatar"
              :auto-upload="false">
                <i class="el-icon-plus imgs-uploader-icon" aria-hidden="true"></i>
                <div slot="file" slot-scope="{file}">
                  <img class="el-upload-list__item-thumbnail" :src="file.url" alt="">
                  <span class="el-upload-list__item-actions">
                    <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                      <i class="el-icon-zoom-in"></i>
                    </span>
                    <span class="el-upload-list__item-delete" @click="handleRemove(file)">
                      <i class="el-icon-delete"></i>
                    </span>
                  </span>
                </div>
            </el-upload>
            <p class="contract-text d2-mt-10">请保证图片格式正确，且不超过2M</p>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSubmit">提交图片</el-button>
          </el-form-item>
        </el-form>
    </el-dialog>


  </div>
</template>
<script>
  import mainTable from "@/components/main-table/index";
  import * as APIDailycare from '@/api/dailycare'
  import { sex, age, elderlyCategory, sourceType, unixToDate } from "@/utils";
  import { uploadCameraFilePromise, uploadFilePromise, uploadDelete } from '@/api/upload'
  import { teamList } from "@/api/wangge";
  import activityAdd from './components/activity-add'
  import { Notification } from 'element-ui'
  export default {
    name: "helpManager-dailycare-activity-list",
    components: {
      mainTable,
      activityAdd
    },
    data() {
      return {
        loading: false,
        title: '添加图标',
        dialogVisible: false,
        dialogDetailsVisible: false,
        dialogImageVisible: false,
        dialogImageUrl:'',
        prevBtn: '上一页',
        nextBtn: '下一页',
        prevDisabled: false,
        nextDisabled: false,
        dialogImgVisible: false,
        ruleForm: {},
        searchForm: {
          page: 1
        },
        tableList:[],
        pagination: {
          current: 1,
          size: 10,
          total: 0
        },
        tableColumns: [
         {
           index: true,
           fixed: true
         },
         {
           prop: 'title',
           label: '活动名称',
           fixed: true
         },
         {
           prop: 'team_name',
           label: '活动站点'
         },
         {
           prop: 'start_time',
           label: '开始时间',
           width: 200,
           formatter (row, column, cellValue) {
             return unixToDate(cellValue)
           }
         },
         {
           prop: 'end_time',
           label: '结束时间',
           width: 200,
           formatter (row, column, cellValue) {
             return unixToDate(cellValue)
           }
         },
         {
           prop: 'jifen_type',
           label: '积分类型',
           formatter (row, column, cellValue) {
             if (row.jifen_type == '1') {
               return '按次数'
             } else if (row.jifen_type == '2') {
               return '按时长'
             }
           }
         },
         {
           prop: 'jifen_num',
           label: '活动积分',
           formatter (row, column, cellValue) {
             if (row.jifen_type == '1') {
               return cellValue + '/次'
             } else if (row.jifen_type == '2') {
               return cellValue + '/小时'
             }
           }
         },
         {
           slot: 'imgs'
         },
         {
           slot: 'status'
         },
         {
           slot: 'action'
         }
        ],
        key: Math.random(),
        teamList:[],
        imgForm: {},
        fileList: [],
        fileLists: [],
        imageArr:[],
        pageIndex: 0,
        rules: {
          images: [
            {
              required: true,
              message: '请上传活动图片',
              trigger: 'blur'
            }
          ]
        }
      };
    },
    created() {},
    beforeDestroy() {},
    mounted() {
      this.fetchTableList();
      this.teamIndex();

      var userinfo = localStorage.getItem("userdata") || {}
      if(userinfo) {
      	userinfo = JSON.parse(userinfo);
        if(userinfo.facedev.length == 0){
          Notification({
            title: '提示',
            message: '请先设置人员账号绑定人脸设备才能进行人脸识别',
            type: 'warning',
            duration: 5 * 1000
          })
        }
      }
    },
    methods: {
      // 站点列表
      teamIndex () {
        teamList({ page_size: 100 }).then(res => {
          this.teamList = res['data']['list'];
          this.teamList.forEach((item, index, arr) => {
            item['id'] = String(item['id'])
          })
        })
      },
      // 点击”查询“按钮 => 此时缓存查询参数
      onSearch () {
        this.pagination = {
          current: 1,
          size: 10,
          total: 0
        }
        this.fetchTableList()
      },
      load () {
        this.fetchTableList()
      },
      // 手动清空/搜索
      clear () {
        this.fetchTableList({ page: 1 })
      },
      fetchTableList(pageObj) {
        this.loading = true
        this.searchForm = {
          ...this.searchForm,
          ...pageObj
        }
        if(this.searchForm.hasOwnProperty('status') && !this.searchForm.status){
          delete this.searchForm.status;
        }
        APIDailycare.riactivityList(this.searchForm).then((resp) => {
          if (resp.code == 200) {
            const { list = [], total = 0 } = resp.data;
            this.tableList = list || []
            this.pagination.total = total;
          }
        }).finally(() => {
         this.loading = false
        });
      },
      edit (row) {
        this.title = '编辑活动';
        this.key = Math.random();
        this.dialogVisible = true
        this.ruleForm = {
          ...row,
          ...{
            start_time: unixToDate(row.start_time),
            end_time: unixToDate(row.start_time)
          }
         };
      },
      handleAdd() {
        this.title = '新增活动';
        this.dialogVisible = true;
        this.key = Math.random();
        this.ruleForm = { type: '1' };
      },
      startActivity(row){
        // this.ruleForm = { ...row };
        // this.dialogDetailsVisible = true;
        // this.$router.push({ path: '/dailycareActivityDetail/' + row.id })
        this.$router.push({
          path: "/dailycareActivityDetail",
          query:{ id: row.id}
        });
      },
      shenhe(row) {
        this.$confirm("确定要审核通过该活动吗?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            APIDailycare.activityAgree({ id: row.id }).then((resp) => {
              if (resp.code == 200) {
                this.$message({ type: "success", message: "审核通过!"});
                this.fetchTableList();
              }
            });
          })
          .catch(() => {
          });
      },
      cancelOrder(row) {
        this.$confirm("确定删除该条数据, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            APIDailycare.riactivityDelete({ id: row.id }).then((resp) => {
              if (resp.code === 200) {
                this.$message({ type: "success", message: "删除成功!"});
                this.fetchTableList();
              }
            });
          })
          .catch(() => {
          });
      },
      // 上一页
      prev () {
        this.pageIndex--
        if (this.pageIndex === 0) {
          this.prevDisabled = true
          this.nextDisabled = false
        } else {
          this.prevDisabled = false
        }
        this.dialogImageUrl = this.imageArr[this.pageIndex]
      },
      // 下一页
      next () {
        this.pageIndex++
        if (this.pageIndex === (this.imageArr.length - 1)) {
          this.nextDisabled = true
          this.prevDisabled = false
        } else {
          this.nextDisabled = false
        }
        this.dialogImageUrl = this.imageArr[this.pageIndex]
      },
      handleBigImage (item) {
        this.dialogImageVisible = true;
        this.pageIndex = 0;
        this.dialogImageUrl = item.img[0]
        this.imageArr = item.img || []
        this.prevDisabled = true
        if (item.img && item.img.length > 1) {
          this.nextDisabled = false
        } else {
          this.prevDisabled = true
          this.nextDisabled = true
        }
      },
      closeImgVisible () {
        this.fileLists = []
        this.fileList = []
      },
      addImg (row) {
        this.dialogImgVisible = true
        this.imgForm = {
          ...this.imgForm,
          ...{ id: row.id }
        }
        if (row.img && row.img.length !== 0) {
          row.img.forEach((item, index) => {
            this.fileLists.push({
              name: index,
              url: item
            })
            this.fileList.push({
              name: index,
              url: item
            })
          })
        }
      },
      onSubmit () {
        const imgs = []
        this.fileLists.forEach(item => {
          imgs.push(item.url)
        })
        if (this.imgForm.images) {
          this.$refs.imgForm.clearValidate(['images'])
        }
        const form = Object.assign({}, this.imgForm, { img: imgs.join(',') })
        APIDailycare.riactivityImg(form).then(res => {
          this.dialogImgVisible = false
          this.fileList = []
          this.fileLists = []
          this.fetchTableList()
        })
      },
      // 上传图片
      changePictureUploadAvatar (file, fileList) {
        this.$refs.imgForm.clearValidate(['images'])
        this.imgForm.images = '1'
        this.fileList = fileList
        uploadFilePromise(file).then(res => {
          this.fileLists.push({
            name: file.name,
            url: res.data
          })
        })
      },
      // 放大图片
      handlePictureCardPreview (file) {
        this.dialogImageUrl = file.url
        this.dialogImageVisible = true
      },
      // 删除图片
      handleRemove (file) {
        this.fileLists.forEach((item, index) => {
          if (item.name === file.name) {
            this.fileList.splice(index, 1)
            this.fileLists.splice(index, 1)
            uploadDelete({ url: item.url })
          }
        })
        if (this.fileLists.length === 0) {
          this.imgForm.images = ''
        }
      },
    },
  };
</script>
<style lang="scss" scoped>
  .index-container {
    box-sizing: border-box;
    width: 100%;
    padding: 0 30px !important;
    margin: 0 !important;
    background: #fff !important;

    .main-header {
      padding-top: 4px;
      margin-bottom: 24px;

      .search {
        display: inline-block;

        .search-title {
          flex: 0 0 48px;
          width: 48px;
          font-size: 16px;
          line-height: 36px;
          color: #333;
        }
      }

      .search > div {
        display: inline-block;
        margin-left: 20px;
      }
    }
    .task-icon-img{
      width: 80px;
      height: 80px;
    }
  }

  .form-footer {
    padding-left: 100px;
  }

  .dialog-main {
    .table-do {
      margin-bottom: 15px;
    }

    ::v-deep {
      th {
        .cell {
          color: #fff;
        }
      }
    }
  }
  .contract-icon-img{
    width: 40px;
    height: 40px;
    cursor: pointer;
  }
</style>
